package com.yuneec.droneservice.command;

import android.util.Log;

import com.MAVLink.yuneec.msg_mav_rc_cmd_ack;
import com.yuneec.droneservice.model.CameraScanResult;
import com.yuneec.droneservice.request.IResponse;

import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by gjw on 2017/3/27.
 */

public class ScanCamera extends BaseCommand {

    public ScanCamera() {
        super(MAV_RC_COMMAND.MAV_RC_CMD_SCAN_CAMERA);
    }

    @Override
    protected short[] body() {
        return null;
    }

    @Override
    public IResponse<CameraScanResult[]> toResponse(msg_mav_rc_cmd_ack ack) {
        int code = ack.code;
        Log.d("zzd_aoa", "res:scan camera    code:" + code);
        IResponse<CameraScanResult[]> response = new IResponse(ids(), code);
        if (code == MAV_RC_ERROR_CODE.MAV_RC_ERR_SUCCESS) {
            try {
                short[] data = ack.params;
                if (data == null || data.length == 0) {
                    Log.d("zzd_aoa", "camera_buf is null or length = 0");
                    response.setCode(MAV_RC_ERROR_CODE.MAV_RC_ERR_UNKNOW);
                    return response;
                }

                int count = data[0] & 0xFF;
                Log.d("zzd_aoa", "ssid count:" + count);
                List<CameraScanResult> cameraWifi = new ArrayList<>();
                if (count > 0) {
                    try {
                        int skip = 1;
                        for (int i = 0; i < count; i++) {
                            CameraScanResult camera = new CameraScanResult();
                            int ssidLen = uIntArrayToUShort(ack.params, skip);
                            skip += 2;
                            byte[] ssid = uIntArrayToByteArray(ack.params, skip, ssidLen);
                            skip += ssid.length;
                            String strSSID = new String(ssid, Charset.forName("utf8"));
                            camera.setSsid(strSSID);

                            camera.setFrequency(uIntArrayToUShort(ack.params, skip));
                            skip += 2;
                            camera.setSignalLevel(uIntArrayToUShort(ack.params, skip));
                            skip += 2;
                            cameraWifi.add(camera);
                        }
                    } catch (Exception e) {
                        Log.e("zzd_aoa", "scan camera error! Ignore!");
                    }
                }
                CameraScanResult[] params = cameraWifi.toArray(new CameraScanResult[cameraWifi.size()]);
                response.setParam(params);
            } catch (Exception e) {
                response.setCode(MAV_RC_ERROR_CODE.MAV_RC_ERR_UNKNOW);
                Log.d("zzd_aoa", "scan camera res parse error!!!");
                e.printStackTrace();
            }
        } else {
            Log.d("zzd_aoa", "scan error:" + response.getCode());
        }
        return response;
    }
}
